/*****************************************************************************************
**  Author:dgz master
**  Contact：jiduxiong@dagongzao.com
**
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码

import { da } from "element-plus/es/locale/index.mjs";

let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: "",
    gridBody: "",
    gridFooter: "",
    //新建、编辑弹出框扩展组件
    modelHeader: "",
    modelBody: "",
    modelRight: "",
    modelFooter: ""
  },
  tableAction: "", //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
     //下面这些方法可以保留也可以删除
    onInit() {  //框架初始化配置前，
        //示例：在按钮的最前面添加一个按钮
        //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
        //     name: "按钮", //按钮名称
        //     icon: "el-icon-document", //按钮图标：https://element.eleme.cn/#/zh-CN/component/icon
        //     type: "primary", //按钮样式:https://element-plus.gitee.io/zh-CN/component/button.html
        //     //color:"#eee",//自定义按钮颜色
        //     onClick: function () {
        //       this.$Message.success("点击了按钮");
        //     }
        //   });

        //示例：设置修改新建、编辑弹出框字段标签的长度
        // this.boxOptions.labelWidth = 150;
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      
      this.boxButtons.unshift({
        name: "计算",
        icon: "el-icon-plus",
        type: "primary",       
        onClick: () =>{
          this.complete();
          // this.up_to_mes()
          console.log("计算按钮！！！")
        }
      })
    },
    complete(anniu_pro){
      if(this.editFormFields["Level"] == "厂级"){
        console.log("厂级数据")
        this.getInfoFromMes()
      }else{
        console.log("工段级数据")
      }

    },
    getInfoFromMes(){
      console.log("LLL")
      let start_data = ""
      let end_data = ""
      if(this.editFormFields["DateLevel"] == "月度"){
        console.log("月度",this.editFormFields["DateLevel"])
        console.log("月度",this.editFormFields["DateLevel"],this.editFormFields.Data)
        const dateStr = this.editFormFields["Data"];
        const dateArray = dateStr.split("-");

        console.log(dateArray,dateArray[1]); // 输出: ["2025", "05", "30"]
        // const newstrdata = dateArray[0]+""
        const { startDate, endDate } = this.getDateRangeUTC(dateStr);
        console.log("开始日期:",startDate,"   结束日期：",endDate) 
        start_data = startDate
        end_data = endDate
        const loadingInstance = this.$loading({
                          lock: true,
                          text: '同步MES数据中···',
                          spinner: 'el-icon-loading',
                          background: 'rgba(247, 237, 237, 0.7)'
                        });
      
        
      }else{
        console.log("日度",this.editFormFields["DateLevel"])
        const currentDate = this.editFormFields["Data"];
        const { startTime, endTime } = this.getAdjustedTimesDay(currentDate); 
        start_data = startTime
        end_data = endTime
        console.log("开始日期:",startTime,"   结束日期：",endTime)
      }
      console.log("日期：",start_data,end_data,this.editFormFields.DateLevel)
      const loadingInstance = this.$loading({
                          lock: true,
                          text: '同步MES数据中···',
                          spinner: 'el-icon-loading',
                          background: 'rgba(247, 237, 237, 0.7)'
                        });
      this.http.get('api/materialfactorycost/GetMaterialPro',
                          {datalevel:this.editFormFields.DateLevel,start_data:start_data,end_data:end_data}).then((reslut) => {
                          console.log("GGGGG");
                          console.log(this.editFormFields.order_name);
                          console.log('同步成功:', reslut);
                          var total_pro = 0
                          var rows1 = reslut["rows"]
                          console.log(rows1.type)
                          for(let i=0;i<rows1.length;i++){
                            total_pro += reslut["rows"][i]["blank_weight"]
                          }
                          console.log("总产量：",total_pro)       
                          this.editFormFields["ToalProduc"] = total_pro.toFixed(4)
                          this.http.get('api/materialfactorycost/get_db_eng',
                              {datalevel:this.editFormFields.DateLevel,start_data:this.editFormFields.Data}).then((reslut) => {

                              console.log("总电量",reslut)
                              this.editFormFields["Energe"] = reslut[0].toFixed(4)
                              console.log(parseFloat(this.editFormFields.TotalCost),parseFloat(this.editFormFields.total_pro))
                              if(this.editFormFields.TotalCost == null){
                                console.log("空的")
                              }else{
                                console.log("不是空的")
                              }
                              console.log(1000/256,parseFloat((this.editFormFields.TotalCost != null ? parseFloat(this.editFormFields.TotalCost):0) / parseFloat(this.editFormFields.ToalProduc)),0/136553.099)
                              this.editFormFields["PerCost"] = (parseFloat((this.editFormFields.TotalCost != null ? parseFloat(this.editFormFields.TotalCost):0) / parseFloat(this.editFormFields.ToalProduc))).toFixed(4)
                              this.editFormFields["PerEng"] = (reslut[0].toFixed(4) / this.editFormFields["ToalProduc"]).toFixed(4)
                              this.editFormFields["PerGas"] = (((this.editFormFields["YGas"] != null ? parseFloat(this.editFormFields.YGas):0)+(this.editFormFields["NGas"]  != null ? parseFloat(this.editFormFields.NGas):0)) / parseFloat(this.editFormFields.ToalProduc)).toFixed(4)
                              if(this.editFormFields["Perstime"] != null){
                                this.editFormFields["PerPeo"] = ((this.editFormFields["ToalProduc"] != null ? parseFloat(this.editFormFields.ToalProduc):0) / (this.editFormFields["Perstime"] != null ? parseFloat(this.editFormFields.Perstime):0)).toFixed(4)
                              }else{
                                this.editFormFields["PerPeo"] = 0
                              }
                              loadingInstance.close();
                            }).catch((error) => {
                                console.error('同步失败:', error);
                                loadingInstance.close();
                            });
                          // loadingInstance.close();
                        }).catch((error) => {
                            console.error('同步失败:', error);
                            loadingInstance.close();
                        });
      
    },
    getAdjustedTimesDay(dateStr) {
      // 解析输入日期
      const [year, month, day] = dateStr.split('-').map(Number);      
      // 创建当前日期的 UTC 时间对象
      const baseDate = new Date(Date.UTC(year, month - 1, day));      
      // 计算当前日期的 00:00:00 UTC 减去 8 小时
      const startTime = new Date(Date.UTC(
        baseDate.getUTCFullYear(),
        baseDate.getUTCMonth(),
        baseDate.getUTCDate(),
        -8,  // 减去 8 小时
        0,
        0
      ));
      
      // 计算当前日期的 23:59:59 UTC 减去 8 小时
      const endTime = new Date(Date.UTC(
        baseDate.getUTCFullYear(),
        baseDate.getUTCMonth(),
        baseDate.getUTCDate(),
        23 - 8,  // 23点减8小时 = 15点
        59,
        59
      ));
      
      // 返回格式化后的字符串
      return {
        startTime: this.formatDateDay(startTime),
        endTime: this.formatDateDay(endTime)
      };
    },
    formatDateDay(date) {
      const year = date.getUTCFullYear();
      const month = String(date.getUTCMonth() + 1).padStart(2, '0');
      const day = String(date.getUTCDate()).padStart(2, '0');
      const hours = String(date.getUTCHours()).padStart(2, '0');
      const minutes = String(date.getUTCMinutes()).padStart(2, '0');
      const seconds = String(date.getUTCSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    getDateRangeUTC(dateStr) {
      const current = new Date(dateStr);

      // 计算上个月24号00:00:00并减去8小时
      const lastMonth24 = new Date(current.getFullYear(), current.getMonth() - 1, 24);
      lastMonth24.setHours(lastMonth24.getHours() - 8);

      // 计算当前月23号23:59:59并减去8小时
      const currentMonth23 = new Date(current.getFullYear(), current.getMonth(), 23, 23, 59, 59);
      currentMonth23.setHours(currentMonth23.getHours() - 8);

      // 格式化输出结果
      console.log("上个月24号00:00:00减8小时: ", this.formatDate(lastMonth24));
      console.log("当前月23号23:59:59减8小时: ", this.formatDate(currentMonth23));
      
      // 格式化为 UTC 时间字符串
      return {
        startDate:  this.formatDate(lastMonth24),
        endDate: this.formatDate(currentMonth23)
      };
    },
    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true;
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
    delBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
   addAfter(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      //添加后刷新字典
      
      return true;
    },
    updateAfter(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      //添加后刷新字典
      
      return true;
    },
    delAfter(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      //添加后刷新字典
      
      return true;
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=="Add";
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段="xxx";
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      this.editFormFields["Data"] = year+"-"+month+"-"+day
      console.log(year+"-"+month+"-"+day)
      this.editFormFields["Level"] = "厂级"
      this.editFormFields["DataType"] = "变动成本"
      this.editFormFields["DateLevel"] = "月度"
    }
  }
};
export default extension;
